#include <iostream>
#include <string>
#include <ctime>
#include "Socket.hpp"
#include "Protocal.hpp"

using namespace std;

void Usage(string proc)
{
    cout << proc << "[ ip + port]" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    srand(time(nullptr));

    string opers = "+-*/%=";

    Sock sock;
    sock.Socket();

    bool r = sock.Connect(ip, port);
    if (!r)
        return 1;

    int cnt = 1;
    string buffer_stream;
    while (cnt <= 10)
    {
        cout << "---------------------执行的第" << cnt << "次" << endl;
        int x = rand() % 5 + 1;
        int y = rand() % 4;
        char op = opers[rand() % opers.size()];

        Request req(x, y, op);

        string package;
        req.Serialize(&package);
        package = Encode(package);

        write(sock.sockfd_, package.c_str(), package.size());

        char buffer[1024];

        int n = read(sock.sockfd_, buffer, 1024);
        if (n > 0)
        {
            buffer[n] = 0;
            buffer_stream += buffer;

            string message;
            r = Decode(buffer_stream, &message);
            if (!r)
                return 1;

            Respone resp;
            resp.Deserialize(message);

            resp.Printf(); // 打印
        }
        cout << "-----------------------" << endl;
        sleep(1);

        cnt++;
    }

    sock.Close();
    return 0;
}
